import { http } from "@/utils/http";
import { PageParams } from "./common";

export type UserResult = {
  success: boolean;
  data: {
    /** 头像 */
    avatar: string;
    /** 用户名 */
    username: string;
    /** 昵称 */
    nickname: string;
    /** 当前登录用户的角色 */
    roles: Array<string>;
    /** 按钮级别权限 */
    permissions: Array<string>;
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
  };
};

export type RefreshTokenResult = {
  success: boolean;
  data: {
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
  };
};

/** 登录 */
export const getLogin = (data?: object) => {
  return http.request<UserResult>("post", "/login", { data });
};

/** 刷新`token` */
export const refreshTokenApi = (data?: object) => {
  return http.request<RefreshTokenResult>("post", "/refresh-token", { data });
};

/**
 * 后台管理响应数据格式
 */
export type ResponseData<T = any> = {
  code: number;
  message: string;
  data: T;
};

/**
 * 后台管理登录相应数据
 */
export type LoginResponseData = {
  token: string;
  name: string;
  account: string;
  rolePermission: {
    hasAll: boolean;
    permissions: string[] | null;
  };
};

/**
 * 后台管理登录接口
 */
export const loginApi = (data: { account: string; password: string }) => {
  return http.request<ResponseData<LoginResponseData>>(
    "post",
    "/api/platform/login",
    { data }
  );
};

/**
 * 后台管理退出登录接口
 */
export const logoutApi = () => {
  return http.request<ResponseData>("post", "/platform/logout");
};

/**
 * 权限列表类型
 */
export type PermissionItem = {
  code: string;
  description: string;
};

/**
 * 获取所有权限列表
 */
export const getPermissonList = () => {
  return http.request<ResponseData<PermissionItem[]>>(
    "get",
    "/platform/role/permissions"
  );
};

/**
 * 用户数据格式
 */
export type User = {
  records: {
    id: number;
    avatar: string;
    nickname: string;
    phone: string;
    openId: string;
    gmtCreate: string;
  }[]
  total: number;
  pageNum: number;
  pageSize: number;
}
/**
 * 分页查询用户列表
 */
export const queryUserList = (data: PageParams) => {
  return http.request<ResponseData<User>>(
    "post",
    "/api/platform/user/page",
    { data }
  );
}